//
//  XSJJumpVCTool.m
//  XV
//
//  Created by apple on 03/04/2019.
//  Copyright © 2019 XR. All rights reserved.
//

#import "XSJJumpVCTool.h"
#import "CommonWebVC.h"
#import "SVProgressHUD.h"
#import "MJExtension.h"
//#import "Reachability.h"
#import "UserInfoModel.h"

#import "TYShowAlertView.h"
#import "LBXPermission.h"
#import "BDDownloadManager.h"

#import "TZImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <Photos/Photos.h>


@interface XSJJumpVCTool()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>

@property (strong, nonatomic) CLLocation *location;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@end


@implementation XSJJumpVCTool

+ (instancetype)sharedManager {
    static XSJJumpVCTool *_manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    
    return _manager;
}


//跳转到网页界面
+(void)to_WebVC:(NSString*)url title:(NSString*)title srcVC:(UIViewController*)srcVC
{
    CommonWebVC* vc = [[CommonWebVC alloc]initWithURLString:title title:title];
    [srcVC.navigationController pushViewController:vc animated:YES];
}


//跳转到聊天界面
+(void)to_ChatVC:(NSString*)mid srcVC:(UIViewController*)srcVC
{
    
}


//跳转到视频聊天界面
-(void)to_VideoChatVC:(NSString*)mid srcVC:(UIViewController*)srcVC
{
    
}


-(void)toVChat:(NSString*)mid srcVC:(UIViewController*)srcVC
{

}




+ (BOOL)checkRTSCondition
{
    BOOL result = YES;
    
//    if (![[Reachability reachabilityForInternetConnection] isReachable])
//    {
//        [SVProgressHUD showInfoWithStatus:@"请检查网络"];
//        result = NO;
//    }
    return result;
}


//跳转到充值界面
+(void)to_RechargeVC:(UIViewController*)srcVC
{
    
}

//播放音频
+(void)to_PlayVoice:(NSString*)voiceUrl srcVC:(UIViewController*)srcVC
{
//    //先下载到本地再播放
//    BDDownloadModel *bdmodel = [[BDDownloadManager manager] modelWithURLString:voiceUrl];
//    if ([[BDDownloadManager manager] isDownloadCompletedWithModel:bdmodel])
//    {
//        if ([NIMSDK sharedSDK].mediaManager.isPlaying)
//        {
//            //停止播放音频
//            [[NIMSDK sharedSDK].mediaManager stopPlay];
//        }
//        else
//        {
//            //播放音频
//            [[NIMSDK sharedSDK].mediaManager play:bdmodel.filePath];
//        }
//
//    }
//    else
//    {
//        [[BDDownloadManager manager] startModel:bdmodel progress:nil state:^(BDDownloadState state, NSString *filePath, NSError *error)
//         {
//             if (state==BDDownloadStateCompleted)
//             {
//                 //播放音频
//                 [[NIMSDK sharedSDK].mediaManager play:filePath];
//             }
//         }];
//    }
}

//播放视频
+(void)to_PlayVideo:(id)videoCallModel vid:(NSString*)vid srcVC:(UINavigationController *)naviController
{
//    XVVideoPlayerVC* vc = [[XVVideoPlayerVC alloc]init];
//    [naviController pushViewController:vc animated:YES];
}



//跳转到图片选择或拍照视频界面(多张图片选择时不能剪)
-(void)to_MediaCameraVC:(UIViewController*)srcVC maxCount:(NSInteger)maxCount isImage:(BOOL)isImage isSrcImage:(BOOL)isSrcImage isVideo:(BOOL)isVideo isClip:(BOOL)isClip isCircle:(BOOL)isCircle isAlert:(BOOL)isAlert completion:(nullable MediaCameraBlock)completion
{
    self.srcVC = srcVC;
    self.maxCount = maxCount;
    self.mediaCameraOK = completion;
    self.isImage = isImage;
    self.isSrcImage = isSrcImage;
    self.isVideo = isVideo;
    self.isClip = isClip;
    self.isCircle = isCircle;
    self.isAlert = isAlert;
    
    if (self.isAlert==NO)
    {
        [self pushTZImagePickerController];
        return;
    }
    
    ZWeakSelf
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    NSString *takePhotoTitle = @"拍照";
    if (isVideo)
    {
        takePhotoTitle = @"拍摄";
    }
    UIAlertAction *action = [UIAlertAction actionWithTitle:takePhotoTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf takePhoto];
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf pushTZImagePickerController];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertController addAction:action];
    [alertController addAction:action1];
    [alertController addAction:action2];
    
    [srcVC presentViewController:alertController animated:YES completion:nil];
}


-(void)okImages:(NSArray*)images assets:(NSArray *)assets isOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    if (self.mediaCameraOK)
    {
        self.mediaCameraOK(images,nil);
    }
}


-(void)okVideos:(UIImage*)coverImage asset:(PHAsset *)asset
{
    if (self.mediaCameraOK)
    {
        self.mediaCameraOK(@[asset],nil);
    }
}



#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController
{
    // 从相册中选取
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxCount delegate:self];
    
    imagePickerVc.allowPickingImage = self.isImage;
    imagePickerVc.allowPickingVideo = self.isVideo;
    imagePickerVc.allowPickingOriginalPhoto = self.isSrcImage;
    //如果没有让用户选择拍摄那么在选择时可以拍
    imagePickerVc.allowTakePicture = !self.isAlert;
    imagePickerVc.allowTakeVideo = !self.isAlert;
    //imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    
    //导航栏返回
    imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
    // 导航栏改为白色
    imagePickerVc.navigationBar.barTintColor = [UIColor whiteColor];
    // 其它文字/icon颜色改为黑色
    imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    
    /// 5. 单选模式,maxImagesCount为1时才生效
    if (self.isClip)
    {
        imagePickerVc.showSelectBtn = NO;
        imagePickerVc.allowCrop = YES;
        imagePickerVc.needCircleCrop = self.isCircle;
        // 设置竖屏下的裁剪尺寸
        NSInteger left = 30;
        NSInteger widthHeight = LL_ScreenWidth - 2 * left;
        NSInteger top = (LL_ScreenHeight - widthHeight) / 2;
        imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
        imagePickerVc.scaleAspectFillCrop = YES;
    }
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片或者视频
    
    ZWeakSelf
    if (self.isVideo)
    {
        [imagePickerVc setDidFinishPickingVideoHandle:^(UIImage *coverImage, PHAsset *asset)
        {
            [weakSelf okVideos:coverImage asset:asset];
        }];
    }
    else
    {
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto)
         {
             [weakSelf okImages:photos assets:assets isOriginalPhoto:isSelectOriginalPhoto];
         }];
    }
    
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.srcVC presentViewController:imagePickerVc animated:YES completion:nil];
}


#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self.srcVC presentViewController:alertController animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self.srcVC presentViewController:alertController animated:YES completion:nil];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}


// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];
        if (self.isVideo) {
            [mediaTypes addObject:(NSString *)kUTTypeMovie];
        }
        if (self.isImage) {
            [mediaTypes addObject:(NSString *)kUTTypeImage];
        }
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self.srcVC presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    [tzImagePickerVc showProgressHUD];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSDictionary *meta = [info objectForKey:UIImagePickerControllerMediaMetadata];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image meta:meta location:self.location completion:^(PHAsset *asset, NSError *error){
            [tzImagePickerVc hideProgressHUD];
            if (error) {
                NSLog(@"图片保存失败 %@",error);
            } else {
                TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
                if (self.isClip) { // 允许裁剪,去裁剪
                    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                        [self okImages:@[cropImage] assets:asset isOriginalPhoto:self.isSrcImage];
                    }];
                    imagePicker.allowPickingImage = NO;
                    imagePicker.needCircleCrop = YES;
                    imagePicker.circleCropRadius = 100;
                    [self.srcVC presentViewController:imagePicker animated:YES completion:nil];
                } else {
                    [self okImages:@[image] assets:@[assetModel.asset] isOriginalPhoto:self.isSrcImage];
                }
            }
        }];
    } else if ([type isEqualToString:@"public.movie"]) {
        NSURL *videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
        if (videoUrl) {
            [[TZImageManager manager] saveVideoWithUrl:videoUrl location:self.location completion:^(PHAsset *asset, NSError *error) {
                [tzImagePickerVc hideProgressHUD];
                if (!error) {
                    TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
                    [[TZImageManager manager] getPhotoWithAsset:assetModel.asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                        if (!isDegraded && photo) {
                            
                            [self okVideos:@[photo] asset:assetModel.asset];
                        }
                    }];
                }
            }];
        }
    }
}


#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.srcVC.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.srcVC.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
        BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}



@end
